<template>
  <a-card :bordered="false" :style="{ height: '100%' }">
    <a-row :gutter="24">
      <a-col :md="4">
        <a-list itemLayout="vertical" :dataSource="roles">
          <a-list-item slot="renderItem" slot-scope="item, index" :key="index">
            <a-list-item-meta :style="{ marginBottom: '0' }">
              <span slot="description" style="text-align: center; display: block">{{ item.roleDesc }}</span>
              <a slot="title" style="text-align: center; display: block" @click="edit(item)">{{ item.roleName }}</a>
            </a-list-item-meta>
          </a-list-item>
        </a-list>
      </a-col>
      <a-col :md="20">
        <div style="max-width: 800px">
          <a-divider v-if="isMobile()" />
          <div v-if="mdl.id">
            <h3>角色：{{ mdl.name }}</h3>
          </div>
          <a-form :form="form" :layout="isMobile() ? 'vertical' : 'horizontal'">
            <a-form-item label="唯一键" v-show="false">
              <a-input v-decorator="[ 'roleId', {rules: []} ]" placeholder="请填写唯一键" disabled="disabled"/>
            </a-form-item>
            <a-form-item label="唯一标识">
              <a-input
                v-decorator="[ 'roleCode', {rules: [{ required: true, message: '唯一标识不能为空' }, { max: 10, message: '唯一标识不能超过10个字' }]} ]"
                placeholder="请填写唯一标识"
                :disabled="state.disabled"/>
            </a-form-item>

            <a-form-item label="角色名称">
              <a-input v-decorator="[ 'roleName', {rules: [{ required: true, message: '角色名称不能为空' }, { max: 10, message: '角色名称不能超过10个字' }]} ]" placeholder="请填写角色名称" />
            </a-form-item>

            <a-form-item label="状态">
              <a-select v-decorator="[ 'status', {rules: [{ required: true, message: '角色状态不能为空' }]}]">
                <a-select-option value="NORMAL">正常</a-select-option>
                <a-select-option value="DISABLE">禁用</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="备注说明">
              <a-textarea :row="3" v-decorator="[ 'roleDesc', {rules: [{ required: true, message: '角色描述不能为空' }, { max: 20, message: '角色描述不能超过20个字' }]} ]" placeholder="请填写角色描述" />
            </a-form-item>
            <a-form-item style="margin-top:24px;">
              <a-button
                size="small"
                type="primary"
                v-show="state.addBtnShow"
                :loading="state.submitBtn"
                :disabled="state.submitBtn"
                @click="addRole">新增</a-button>
              <a-button
                size="small"
                type="primary"
                v-show="!state.addBtnShow"
                :loading="state.updateBtn"
                :disabled="state.updateBtn"
                @click="updateRole">修改</a-button>
              <a-button
                size="small"
                type="primary"
                v-show="!state.addBtnShow"
                :loading="state.permissionBtn"
                :disabled="state.permissionBtn"
                @click="updatePermissionModel">分配权限</a-button>
              <a-button
                size="small"
                type="danger"
                v-show="!state.addBtnShow"
                :loading="state.deleteBtn"
                :disabled="state.deleteBtn"
                @click="deleteRole">删除</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-col>
    </a-row>
    <role-assign-permission-model ref="updatePermissionModel" @ok="refresh" @cancel="refresh"/>
  </a-card>
</template>

<script>
import { getRoleList } from '@/api/manage'
import { mixinDevice } from '@/utils/mixin'
import pick from 'lodash.pick'
import { addRole, updateRole, delRoleById } from '@/api/role'
import RoleAssignPermissionModel from './modules/RoleAssignPermission';

export default {
  name: 'RoleList',
  mixins: [mixinDevice],
  components: {
    RoleAssignPermissionModel
  },
  data () {
    return {
      form: this.$form.createForm(this),
      mdl: {},
      roles: [],
      permissions: [],
      state: {
        addBtnShow: true,
        submitBtn: false,
        updateBtn: false,
        permissionBtn: false,
        deleteBtn: false,
        disabled: false
      }
    }
  },
  created () {
    this.refresh()
  },
  methods: {
    callback (val) {
      console.log(val)
    },
    addRole () {
      const self = this
      self.state.submitBtn = true
      self.form.validateFields((err, values) => {
        if (!err) {
          addRole(values).then(res => {
            if (res.data) {
              self.$notification['success']({
                message: '提示',
                description: '新增成功',
                duration: 2
              })
            } else {
              self.$notification['warning']({
                message: '提示',
                description: '新增失败',
                duration: 2
              })
            }
            setTimeout(() => {
              self.refresh()
            }, 200)
          }).finally(() => {
            self.state.submitBtn = false
          })
        }
      })
    },
    updateRole () {
      const self = this
      self.state.updateBtn = true
      self.form.validateFields((err, values) => {
        if (!err) {
          updateRole(values).then(res => {
            console.log(res)
            if (res.data) {
              self.$notification['success']({
                message: '提示',
                description: '更新成功',
                duration: 2
              })
            } else {
              self.$notification['warning']({
                message: '提示',
                description: '更新失败',
                duration: 2
              })
            }
            setTimeout(() => {
              self.refresh()
            }, 200)
          }).finally(() => {
            self.state.updateBtn = false
          })
        }
      })
    },
    updatePermissionModel () {
      this.$refs.updatePermissionModel.show(this.mdl.roleId)
    },
    deleteRole () {
      const self = this
      self.state.deleteBtn = true
      const roleId = self.form.getFieldValue('roleId')
      if (roleId) {
        delRoleById(roleId).then(res => {
          if (res.data) {
            self.$message.success('删除成功');
          } else {
            self.$message.warning('删除失败');
          }
          setTimeout(() => {
            self.refresh()
          }, 200)
        }).finally(() => {
          self.state.deleteBtn = false
        })
      }
    },
    edit (record) {
      const self = this
      // 新增修改按钮展示
      if (record.roleId === '-1') {
        self.state.addBtnShow = true
        self.state.disabled = false
      } else {
        self.state.addBtnShow = false
        self.state.disabled = true
      }
      console.log('edit:', record)
      self.mdl = Object.assign({}, record)
      self.$nextTick(() => {
        self.form.setFieldsValue(pick(self.mdl, 'roleId', 'roleCode', 'roleName', 'status', 'roleDesc'))
      })
      console.log('this.mdl', self.mdl)
    },
    refresh () {
      getRoleList().then((res) => {
        this.roles = res.data
        this.roles.push(this.defaultRole())
        console.log('this.roles', this.roles)
      })
      this.edit(this.defaultRole())
    },
    defaultRole () {
      return {
        roleId: '-1',
        roleCode: '',
        roleName: '新增角色',
        status: 'NORMAL',
        roleDesc: '新增一个角色'
      }
    }
  }
}
</script>

<style scoped>
button {
  margin-right: 10px;
}
</style>
